import React, { Component } from 'react';
import css from './index.less';
import FilterSearch from '@/components/FilterSearch';
import TableList from '@/components/TableList';
import { Button, message } from 'antd';
import { connect } from 'dva';
import { Link } from 'react-router-dom';
import axios from 'axios';
import AuthButton from '@/components/AuthButton';

type State = {
  selectProject: any;
};
type Props = {
  dispatch: Function;
};
class Department extends Component<Props> {
  state: State = {
    selectProject: {},
  };
  table = null;
  search = null;
  componentDidMount() {
    this.search &&
      this.search.setValue({
        budgetYear: new Date().getFullYear(),
        buildType: null,
        orgName: '',
        page: 0,
        projectName: '',
        projectNo: '',
        size: 10,
      });
  }
  filters = [
    {
      key: 'budgetYear',
      type: 'select',
      label: '选择年份',
      options: this.props.dict.yearList,
    },
    {
      key: 'buildType',
      type: 'select',
      label: '项目性质',
      options: [
        {
          label: '建设',
          value: 'BUILD',
        },
        {
          label: '保障',
          value: 'PURCHASE_SERVICE',
        },
      ],
    },
    {
      key: 'orgName',
      type: 'input',
      label: '业主单位',
    },
    {
      key: 'projectNo',
      type: 'input',
      label: '项目ID',
    },
    {
      key: 'projectName',
      type: 'input',
      label: '项目名称',
    },
  ];
  columns = [
    {
      title: '填报日期',
      dataIndex: 'createTime',
      width: 150,
      format: 'YYYY-MM-DD',
    },
    {
      title: '项目名称',
      dataIndex: ['project', 'name'],
      render: (text, data) => (
        <Button type="link" onClick={() => this.goDetail(data, true)}>
          {text}
        </Button>
      ),
    },
    { title: '项目ID', dataIndex: ['project', 'no'] },
    {
      title: '项目性质',
      dataIndex: ['project', 'buildType'],
      render: text => (text == 'BUILD' ? '建设' : '保障'),
    },
    { title: '业主单位', dataIndex: ['project', 'ownerOrgUnit', 'name'] },
    { title: '预算年份', dataIndex: 'budgetYear' },
    { title: '预算金额（万元）', dataIndex: ['budget', 'total'] },
    {
      title: '操作',
      width: 225,
      render: (text, data) => (
        <div>
          <AuthButton
            type="link"
            key={text}
            role="edit_budget"
            onClick={() => this.goDetail(data, false)}
          >
            编辑
          </AuthButton>
          <AuthButton
            type="link"
            key={text}
            role="del_budget"
            onClick={() => this.delete(data, false)}
          >
            删除
          </AuthButton>
        </div>
      ),
    },
  ];

  goDetail = (data, readOnly) => {
    const url = `projectFillIn/budget/edit?id=${data.uuid ||
      ''}&readOnly=${readOnly || ''}`;
    this.props.dispatch({
      type: '$router/forward',
      payload: {
        url,
      },
    });
  };

  exportTable = () => {
    const values = this.search.getValue();
    values.page = 0;
    values.size = 10;
    axios({
      url: '/api/budget/v1/export',
      method: 'post',
      responseType: 'arraybuffer',
      data: values,
      headers: {
        token: sessionStorage.getItem('token'),
      },
    })
      .then(res => {
        let blob = new Blob([res.data]);
        let link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = decodeURIComponent('资金预算.xlsx');
        link.click();
        message.success('文件已下载');
      })
      .catch(() => {
        message.error('导出异常');
      });
  };
  /**
   * 删除用户
   * @param data
   */
  delete(data) {
    this.props
      .dispatch({
        type: 'base/delete',
        payload: {
          url: '/api/budget/v1/del',
          type: '该预算',
          data,
        },
      })
      .then(res => {
        this.table.fetch();
      });
  }
  render() {
    const { selectProject } = this.state;
    return (
      <div>
        <FilterSearch
          filters={this.filters}
          onSearch={val => this.table.fetch(val)}
          onRef={c => (this.search = c)}
        >
          <AuthButton type="primary" role="add_budget">
            <Link to={{ pathname: '/projectFillIn/budget/edit' }}>添加</Link>
          </AuthButton>
          <AuthButton
            onClick={this.exportTable}
            style={{ marginLeft: 30 }}
            role="export_budget"
          >
            导出
          </AuthButton>
        </FilterSearch>
        <TableList
          post
          rowKey="id"
          onRef={c => {
            this.table = c;
          }}
          columns={this.columns}
          source="/api/budget/v1/query"
        />
      </div>
    );
  }
}

export default connect(state => state.base)(Department);
